<template>
  <div class="ts-modify-pwd">
    <ts-header title="修改密码" back></ts-header>
    <div class="ts-modify-pwd-form">
      <ts-input v-model.trim="formData.password" type="password" label="当前密码" placeholder="请输入"></ts-input>
      <ts-input v-model.trim="formData.new_pwd" type="password" label="新密码" placeholder="请输入"></ts-input>
      <ts-input v-model.trim="formData.new_pwd2" type="password" label="确认新密码" placeholder="请输入"></ts-input>
      <div class="ts-modify-pwd-submit">
        <ts-button @click="updPwd()" class="ts-modify-pwd-btn" size="large" type="primary">确认修改</ts-button>
      </div>
    </div>
  </div>
</template>

<script>
  import objectAssign from 'object-assign'
  import verify from '../../utils/verify'
  import {RESET_PWD} from '../../assets/js/api'

  export default {
    name: 'modifyPwd',
    data() {
      return {
        formData: {
          password: '',
          new_pwd: '',
          new_pwd2: ''
        }
      }
    },
    methods: {
      async updPwd() {
        if (this.checkForm()) {
          let {member_id} = this.$store.state.currentUser;
          let json = await this.$http.post(RESET_PWD, objectAssign(this.formData,
            {member_id}), {show: true});
          if (json.result === 1) {
            let toast = this.$toast('修改成功，请重新登录，跳转中...');
            setTimeout(() => {
              toast.close();
              this.$router.push('/login');
            }, 2000);
          }
        }
      },
      checkForm() {
        let valid = verify.requiredObjProp(this.formData);
        if (!valid.isValid) {
          let {key} = valid;
          if (key === 'password')
            this.$toast('请输入当前密码')
          else if (key === 'new_pwd')
            this.$toast('请输入新密码')
          else if (key === 'new_pwd2')
            this.$toast('请输入确认新密码');
          return false;
        }
        if (!verify.password(this.formData.new_pwd)) {
          this.$toast('密码为6-16位英文数字组合');
          return false;
        }
        let {new_pwd, new_pwd2} = this.formData;
        if (this.formData.new_pwd !== this.formData.new_pwd2) {
          this.$toast('确认密码和新密码不一致');
          new_pwd2 = '';
          return false;
        }
        return true;
      }
    }
  }
</script>

<style lang="scss">
  .ts-modify-pwd {
    background-color: #ffffff;
    .ts-modify-pwd-form {
      padding-top: .10rem;
      .ts-input .ts-left .ts-label {
        width: 2.20rem;
      }
      .ts-modify-pwd-submit {
        padding: .85rem .35rem;
      }
    }
  }
</style>
